package apps.softtech.fastmarket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sileria.android.view.HorzListView;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.fastmarket.adapter.AdapterListProduct1;
import apps.softtech.fastmarket.model.DatabaseHandler;
import apps.softtech.fastmarket.model.Product;
import apps.softtech.fastmarket.model.UserInfo;

public class FragmentTabHome extends Fragment {

	protected static final String URL_PRODUCT =  
			ApplicationConstants.BASE_URL + "product/get_product_by_category_id";
	protected static final String TAG = "TAG_HOME";	private AutoCompleteTextView autoSearch;
	private ImageView imgAdv;
	private HorzListView lvListProduct1, lvListProduct2, lvListProduct3;
	private TextView tvNameList1, tvNameList2, tvNameList3;
	private TextView tvRegister, tvLogin;

	/**
	 * adapter of listview product in home
	 */
	private AdapterListProduct1 mAdapter1, mAdapter2, mAdapter3;
	List<Product> mListProduct1 = new ArrayList<Product>();
	List<Product> mListProduct2 = new ArrayList<Product>();
	List<Product> mListProduct3 = new ArrayList<Product>();
	// private Context mContext;
	private ProgressDialog progress;
	
	/**
	 * bien dung cho adapter load image
	 */
	DisplayImageOptions options;
	String categoryId = "23";
	Activity activity;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_home, container, false);
		
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getActivity()).build();
		ImageLoader.getInstance().init(config);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(0)).build();

		initHome(v);
		setEventHome();
		
		return v;
	}

	private void initHome(View v) {

		tvRegister = (TextView) v.findViewById(R.id.tvRegister);
		tvLogin = (TextView) v.findViewById(R.id.tvLogin);

		autoSearch = (AutoCompleteTextView) v.findViewById(R.id.autoSearch);
		lvListProduct1 = (HorzListView) v.findViewById(R.id.lvProduct);
		lvListProduct2 = (HorzListView) v.findViewById(R.id.lvProduct1);
		lvListProduct3 = (HorzListView) v.findViewById(R.id.lvProduct2);

		tvNameList1 = (TextView) v.findViewById(R.id.tvNameList1);
		tvNameList1 = (TextView) v.findViewById(R.id.tvNameList2);
		tvNameList1 = (TextView) v.findViewById(R.id.tvNameList3);

	}
	
	/**
	 * init listview product best Deals
	 */
	private void initListViewProduct3() {

		mAdapter3 = new AdapterListProduct1(getActivity(), mListProduct3,
				options);
		lvListProduct3.setAdapter(mAdapter3);
	}
	
	/**
	 * init listview product best Deals
	 */
	private void initListViewProduct2() {

		mAdapter2 = new AdapterListProduct1(getActivity(), mListProduct2,
				options);
		lvListProduct2.setAdapter(mAdapter2);
	}
	
	
	
	/**
	 * init for listView product best sale
	 */
	private void initListViewProduct1() {
		mAdapter1 = new AdapterListProduct1(getActivity(), mListProduct1,
				options);
		lvListProduct1.setAdapter(mAdapter1);
	}
	
	/**
	 * method to get list product form server
	 * 
	 * @author MUI
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	private void getProductFromServer(String gcmId, String categoryId) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		JSONObject jsonOject = new JSONObject();

		try {
			jsonOject.put("st_GcmId", gcmId);
			jsonOject.put("st_CategoryId", categoryId);

		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		params.add(new BasicNameValuePair("data", jsonOject.toString()));

		new AsyncTask<List<NameValuePair>, Void, String>() {

			protected void onPreExecute() {

			};

			@Override
			protected String doInBackground(List<NameValuePair>... params) {
				HttpRequest request = new HttpRequest();
				String result = request.makeServiceCall(URL_PRODUCT,
						HttpRequest.POST, params[0]);
				return result;
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);

				try {
					Log.i(TAG, "result in tab home: " + result);
					JSONObject json = new JSONObject(result);
					JSONArray jsonData = new JSONArray();
					if (json.getString("success") != null) {
						String check = json.getString("success");
						if (Integer.parseInt(check) == 1) {
							jsonData = json.getJSONArray("data");
							Log.i(TAG, jsonData.toString());

							/*
							 * lay data tra ve tu response
							 */
							for (int i = 0; i < jsonData.length(); i++) {
								JSONObject jsonList = new JSONObject(jsonData
										.getJSONObject(i).toString());

								Product product = new Product();
								product.setAvatarPath(ApplicationConstants.BASE_URL_IMAGE + jsonList.getString("st_AvatarPath"));
								Log.i(TAG, "avatar: " + product.getAvatarPath());

								product.setDescription(jsonList
										.getString(Product.CREATED_DATE));
								mListProduct1.add(product);
							}
							
							if (mListProduct1.size() > 0) {
								initListViewProduct1();
							}

						} else if (Integer.parseInt(check) == 0) {
							Log.i(TAG, "success:0");
							Toast.makeText(getActivity(), "request failed", Toast.LENGTH_SHORT).show();
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}.execute(params);

	}

	


	@SuppressWarnings("unused")
	private void getProductFromApp() {
		DatabaseHandler db = new DatabaseHandler(getActivity());
		mListProduct1 = db.getProduct(null, null, null, null, null);db.close();

	}

	

	/**
	 * @author MUI method to set event for view in this layout
	 */
	private void setEventHome() {

		/*
		 * chuyen sang trang login
		 */
		tvLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), ActivityLogin.class);
				startActivity(intent);
				getActivity().finish();
			}
		});

		/*
		 * chuyen sang trang register
		 */
		tvRegister.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),
						ActivityRegister.class);
				startActivity(intent);
				getActivity().finish();
			}
		});

		/*
		 * chuyen qua giao dien search
		 */
		autoSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity()
						.getApplicationContext(), ActivitySearch.class);
				startActivity(intent);

			}
		});
	}

	/**
	 * method check internet connection
	 * 
	 * @return
	 */
	private Boolean connectionDetector() {
		ConnectionDetector detector = new ConnectionDetector(getActivity());
		if (detector.isConnectingToInternet()) {
			return true;

		}
		return false;
	}
}